package com.example.android.contactmanager;

import java.io.InputStream;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;

public class AdapterList extends SimpleCursorAdapter {
    private Cursor _cursor;
    private Context _context;
 
    public AdapterList(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        
        _cursor = c;
        _context = context;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
    	super.bindView(view, context, cursor);
    	
        ImageView imageView = (ImageView) view.findViewById(R.id.contact_image_list);
 
        int id = _cursor.getColumnIndex(ContactsContract.Data._ID);
        long contactId = _cursor.getLong(id);
        
        Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
        
        InputStream is = Contacts.openContactPhotoInputStream(_context.getContentResolver(), contactUri);
        
        if(is != null)
        {
	        Bitmap bitmap = BitmapFactory.decodeStream(is);
	        
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			int newWidth = 80;
			int newHeight = 80;
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;
			
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			
			// create the new Bitmap object
			Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
	
	        imageView.setImageBitmap(resizedBitmap);
        }
        else
        	imageView.setImageBitmap(Bitmap.createBitmap(80, 80, Bitmap.Config.ALPHA_8));
    }
}
